//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj成员管理

#import "MembersManageVC.h"
#import "MJArcManageTbvCell.h"
#import "AddMemberVC.h"
#import "MJSearchBarView.h"
#import "MemberInfoVC.h"
#import "ArchivesSectionView.h"
#import "SearchMembersVC.h"
#import "SelectTestItemAlertView.h"
#import "DetectionPeriodtAlertView.h"

@interface MembersManageVC ()<UITableViewDelegate,UITableViewDataSource,ArchivesSectionViewDelegate>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *tempDataArray;
@property (nonatomic, strong) NSMutableArray *firstLetterArray;
@property (assign, nonatomic) NSInteger pageNumber;
@property (weak, nonatomic) IBOutlet UIView *viewContent;
@property (weak, nonatomic) IBOutlet MJSearchBarView *searchBarView;
@property (weak, nonatomic) IBOutlet MJUITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;

@end

@implementation MembersManageVC

- (void)viewDidLoad {
    self.backgroundColorType = BackgroundColorTypeGray;
    [super viewDidLoad];
    
    self.pageNumber = 1;
//    [self requestData];

    MJWeakSelf
    [RACObserve(HealthHelper.shared, homePatientList) subscribeNext:^(NSMutableArray *homePatientList) {
        if(homePatientList.count){
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.dataArray addObjectsFromArray:HealthHelper.shared.homePatientList];
            [weakSelf sortAcronym];
            [weakSelf.tableView reloadData];
        }
        weakSelf.totalLabel.text = [NSString stringWithFormat:@"%ld %@",weakSelf.dataArray.count, MJUILocalizedString(@"members total")];
        [weakSelf showEmptyView];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
 
}

- (void)mj_setUI{
    [super mj_setUI];
     
    MJWeakSelf
    self.mj_titleLocalizable = @"Members Manage";
    NSString *name = UserManager.shared.userModel.userName ?: UserManager.shared.userModel.phoneNumber.mj_securePhoneNumber;
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN || LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU || LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
        self.userNameLabel.text = [NSString stringWithFormat:@"%@ %@",MJUILocalizedString(@"Members of"),name];
    }else{
        self.userNameLabel.text = [NSString stringWithFormat:@"%@ %@",name,MJUILocalizedString(@"Members of")];
    }
   
    
    [self setNavRightItemImage:MJUIImageMake(@"icon_tianjia_app")];
    self.pageNumber = 1;
    self.searchBarView.leftButton.hidden = true;
    self.searchBarView.itemButton.hidden = false;
    [self.searchBarView.itemButton mj_addAction:^(UIButton *button) {
        SearchMembersVC *vc = [[SearchMembersVC alloc]init];
        [weakSelf.navigationController pushViewController:vc animated:NO];
    }];
    MJUITableView *tableView = self.tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = 100;
    [MJArcManageTbvCell registerNibWithTableView:tableView];
    [ArchivesSectionView registerNibWithTableView:tableView];
//    tableView.mj_header = [MJUIRefreshHeader headerWithRefreshingBlock:^{
//       weakSelf.pageNumber = 1;
//       [weakSelf requestData];
//    }];
//    tableView.mj_footer = [MJUIRefreshFooter footerWithRefreshingBlock:^{
//       [weakSelf requestData];
//    }];
   
}
#pragma mark - 方法
- (void)handleRightBarButtonClick {
    AddMemberVC *vc = [[AddMemberVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)handleEmptyButtonClick:(UIButton *)sender{
    [self handleRightBarButtonClick];
}

- (void)requestData{
    
    BOOL flag = self.dataArray.count > 0 ? false:true;
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:@{} requestUri:patient_select requestType:RequestTypeGet showLoading:flag success:^(MJBaseModel *model) {
        
        if (model.code ==  200){
            weakSelf.hideLoading = true;
            NSArray *data = model.data;
            NSMutableArray *modelArray = [NSMutableArray array];
            for (int i = 0; i<data.count; i++) {
                PatientModel *rmodel = [PatientModel yy_modelWithDictionary:data[i]];
                [modelArray addObject:rmodel];
            }
            [weakSelf processData:modelArray];
         }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)processData:(NSArray *)modelArray{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    
    if(self.pageNumber == 1){
        [self.tableView.mj_footer resetNoMoreData];
        [self.dataArray removeAllObjects];
    }
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    [self.dataArray addObjectsFromArray:modelArray];
    [self showEmptyView];
    
    //排序首字母
    [self sortAcronym];
    [self.tableView reloadData];
    self.pageNumber++;
}

- (void)sortAcronym {
    if(self.dataArray.count){
        NSMutableArray *firstLetterArray = [NSMutableArray array];
        for (PatientModel *rmodel in self.dataArray) {
            //俄语排序
            if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
                NSString *firstLetter = rmodel.patientName.mj_firstRuLetter;
                if(![firstLetterArray containsObject:firstLetter]){
                    [firstLetterArray addObject:firstLetter];
                }
            }else{
                NSString *firstLetter = rmodel.patientName.mj_firstLetter;
                if(![firstLetterArray containsObject:firstLetter]){
                    [firstLetterArray addObject:firstLetter];
                }
            }
        }
         //字母排序
        NSArray *newArray = [firstLetterArray sortedArrayUsingSelector:@selector(compare:)];
        self.firstLetterArray = [NSMutableArray array];
        //
        MJCommonModel *model = [[MJCommonModel alloc]init];
        model.title = MJUILocalizedString(@"All");
        model.isSelect = true;
        [self.firstLetterArray addObject:model];
        //
        for (NSString *item in newArray) {
            MJCommonModel *model = [[MJCommonModel alloc]init];
            model.title = item;
            [self.firstLetterArray addObject:model];
        }
        //一句代码 深拷贝
        NSArray <PatientModel *>*deepCopyAry = [NSMutableArray yy_modelArrayWithClass:[PatientModel class] json:[self.dataArray yy_modelToJSONData]];
        self.tempDataArray = [NSMutableArray arrayWithArray:deepCopyAry];
    }
}

- (void)showEmptyView{
    
    if(self.dataArray.count > 0){
        [self hideEmptyView:self.tableView];
        self.searchBarView.hidden = false;
    }else{
        [self showEmptyView:self.tableView emptyStyle:EmptyViewMember];
        self.searchBarView.hidden = true;
    }
}

#pragma mark - ArchivesSectionViewDelegate 代理方法
- (void)collectionViewdidSelectItemAtIndex:(NSInteger)index{
    if(index == 0){
        //一句代码 深拷贝
        NSArray <PatientModel *>*deepCopyAry = [NSMutableArray yy_modelArrayWithClass:[PatientModel class] json:[self.dataArray yy_modelToJSONData]];
        self.tempDataArray = [NSMutableArray arrayWithArray:deepCopyAry];
    }else{
        self.tempDataArray = [NSMutableArray array];
        MJCommonModel *model = self.firstLetterArray[index];
        for (PatientModel *itemModel in self.dataArray) {
            
            if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
                if([itemModel.patientName.mj_firstRuLetter isEqualToString:model.title]){
                    [self.tempDataArray addObject:itemModel];
                }
            }else{
                if([itemModel.patientName.mj_firstLetter isEqualToString:model.title]){
                    [self.tempDataArray addObject:itemModel];
                }
            }
        }
    }
    [self.tableView reloadData];
}

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.tempDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MJWeakSelf
    MJArcManageTbvCell *cell = [MJArcManageTbvCell reuseForTableView:tableView forIndexPath:indexPath];
    PatientModel *patientModel = self.tempDataArray[indexPath.row];
    cell.model = patientModel;
    [cell.detectionImageView mj_addTapActionWithBlock:^{
        [HealthHelper jumpDetectionViewControllerWith:patientModel viewController:weakSelf];
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    MemberInfoVC *vc = [[MemberInfoVC alloc]init];
    PatientModel *model = self.tempDataArray[indexPath.row];
    vc.patientModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(self.firstLetterArray.count > 0){
        NSInteger row = 0;
        if(self.firstLetterArray.count < 10){
            row = 1;
        }else if(self.firstLetterArray.count >= 10 && self.firstLetterArray.count < 20){
            row = 2;
        }else{
            row = 3;
        }
        return 35*row+(row - 1)*6 + 15;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ArchivesSectionView *sectionHeaderView = [ArchivesSectionView reuseForTableView:tableView];
    sectionHeaderView.delegate = self;
    sectionHeaderView.firstLetterArray = self.firstLetterArray;
    return sectionHeaderView;
}

#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
